package com.xiaoxin.yixinai.companyinfo;

import java.text.ParseException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaoxin.yixinai._frame.base.BaseRepository;
import com.xiaoxin.yixinai._frame.base.BaseServiceProxy;
import com.xiaoxin.yixinai._frame.base.PageSupport;
import com.xiaoxin.yixinai._frame.utils.Config;
import com.xiaoxin.yixinai._frame.utils.StringUtils;
import com.xiaoxin.yixinai.companyversion.CompanyVersionService;
import com.xiaoxin.yixinai.dict.DictService;
import com.xiaoxin.yixinai.userinfo.UserInfo;
import com.xiaoxin.yixinai.userinfo.UserInfoRepository;
import com.xiaoxin.yixinai.userinfo.UserInfoService;

@Service
@Transactional
public class CompanyInfoService extends BaseServiceProxy<CompanyInfo> {

	@Resource
	private Config config;
	
	@Resource
	private EntityManager em;

	@Resource
	private CompanyInfoRepository companyInfoRepository;

	@Resource
	private UserInfoRepository userInfoRepository;

	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private DictService dictService;
	
	@Resource
	private CompanyVersionService companyVersionService;

	@Override
	protected BaseRepository<CompanyInfo> getBaseRepository() {
		return companyInfoRepository;
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

	/**
	 * 运营管理-企业管理-列表-总部
	 * 
	 * @param listParams
	 * @param pageable
	 * @return
	 * @throws ParseException
	 */
	@Transactional(readOnly = true)
	public Page<CompanyInfo> findList4HeadQuarter(CompanyInfoListParams listParams, Pageable pageable) {
		List<Object> params = new LinkedList<Object>();

		/* 拼接select语句 */
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT ci.company_id AS companyId, ci.account_manager_name AS accountManagerName ");
		selectSql.append(", ci.agents_id AS agentsId, ci.agents_name AS agentsName ");
		selectSql.append(", ci.company_name AS companyName, ci.industry_id AS industryId ");
		selectSql.append(", ci.sale_name AS saleName, ci.short_name AS shortName ");
		selectSql.append(", ci.address AS address, ci.insert_time AS insertTime ");

		/* 拼接from + where语句 */
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_company_info ci ");
		fromWhereSql.append(appendWhere(listParams, params));

		String orderBySql = "ORDER BY ci.company_id DESC ";

		// 查询列表数据
		return super.findPageBySql(CompanyInfo.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params,
				pageable);
	}

	/**
	 * 运营中心查询公司列表
	 * @param groupId
	 * @param listParams
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<CompanyInfo> findList4OperationCenter(Integer groupId, CompanyInfoListParams listParams, Pageable pageable) {
		List<Object> params = new LinkedList<Object>();

		/* 拼接select语句 */
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT ci.company_id AS companyId, ci.account_manager_name AS accountManagerName ");
		selectSql.append(", ci.agents_id AS agentsId, ci.agents_name AS agentsName ");
		selectSql.append(", ci.company_name AS companyName, ci.industry_id AS industryId ");
		selectSql.append(", ci.sale_name AS saleName, ci.short_name AS shortName ");
		selectSql.append(", ci.address AS address, ci.insert_time AS insertTime ");

		/* 拼接from + where语句 */
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_company_info ci ");
		fromWhereSql.append("INNER JOIN tb_plat_manager pm ON pm.id = ci.agents_id AND (pm.is_sub_account IS NULL OR pm.is_sub_account = 0) ");
		fromWhereSql.append("INNER JOIN tb_plat_group_user pgu ON pgu.user_id = pm.id ");
		fromWhereSql.append("INNER JOIN tb_plat_group pg ON pg.group_id = pgu.group_id AND pg.group_id = ? ");
		params.add(groupId);
		fromWhereSql.append(appendWhere(listParams, params));

		String orderBySql = "ORDER BY ci.company_id DESC ";

		// 查询列表数据
		return super.findPageBySql(CompanyInfo.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params,
				pageable);
	}

	/**
	 * 代理商查询公司列表
	 * @param listParams
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<CompanyInfo> findList4Agent(CompanyInfoListParams listParams, Pageable pageable) {
		List<Object> params = new LinkedList<Object>();
		
		/* 拼接select语句 */
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT ci.company_id AS companyId, ci.account_manager_name AS accountManagerName ");
		selectSql.append(", ci.agents_id AS agentsId, ci.agents_name AS agentsName ");
		selectSql.append(", ci.company_name AS companyName, ci.industry_id AS industryId ");
		selectSql.append(", ci.sale_name AS saleName, ci.short_name AS shortName ");
		selectSql.append(", ci.address AS address, ci.insert_time AS insertTime ");

		/* 拼接from + where语句 */
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_company_info ci ");
		fromWhereSql.append(appendWhere(listParams, params));

		String orderBySql = "ORDER BY ci.company_id DESC ";

		// 查询列表数据
		return super.findPageBySql(CompanyInfo.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params,
				pageable);
	}

	/**
	 * 
	 * @param listParams
	 * @param params
	 * @return
	 */
	private String appendWhere(CompanyInfoListParams listParams, List<Object> params) {

		StringBuffer sql = new StringBuffer();
		if (listParams.getAgentId() != null) {
			sql.append("AND ci.agents_id = ? ");
			params.add(listParams.getAgentId());
		}
		if (listParams.getIndustryId() != null) {
			sql.append("AND ci.industry_id = ? ");
			params.add(listParams.getIndustryId());
		}
		if (StringUtils.isNotEmpty(listParams.getKeyword())) {
			sql.append("AND ( ")
				.append("ci.company_name LIKE ? ")
				.append("OR ci.company_id LIKE ? ")
				.append("OR ci.company_id in ( ")
					.append("SELECT ui.company_id ")
					.append("FROM ")
					.append("(SELECT MIN(user_id) as userId FROM tb_user_info WHERE is_delete = 0 GROUP BY company_id) t0 ")
					.append("INNER JOIN tb_user_info ui ON ui.user_id = t0.userId ")
					.append("WHERE ui.login_name LIKE ? ")
				.append(") ")
			.append(") ");
			params.add("%" + listParams.getKeyword() + "%");
			params.add("%" + listParams.getKeyword() + "%");
			params.add("%" + listParams.getKeyword() + "%");
		}
		if (StringUtils.isNotEmpty(listParams.getProvinceCode())) {
			sql.append("AND ci.province_code = ? ");
			params.add(listParams.getProvinceCode());
		}
		if (StringUtils.isNotEmpty(listParams.getCityCode())) {
			sql.append("AND ci.city_code = ? ");
			params.add(listParams.getCityCode());
		}
		if (sql.length() > 0) {
			sql.delete(0, "AND ".length());
			sql.insert(0, "WHERE ");
		}

		return sql.toString();
	}

	/**
	 * 根据companyIds查询并发数和机器人数
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<Integer, Integer[]> findConcurrentNumAndRobotNum(Set<Integer> companyIds) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT ");
		sql.append("company_id ");
		sql.append(
				",SUM(CASE WHEN concurrent_num is null THEN 1 WHEN concurrent_num=0 THEN 1 ELSE concurrent_num END) as concurrent_num ");
		sql.append(
				", SUM(CASE WHEN robot_num is null THEN 1 WHEN robot_num=0 THEN 1 ELSE robot_num END) as robot_num FROM tb_company_channel ");
		sql.append("WHERE is_delete = 0 AND `channel_status` = 1 AND company_id in (:companyIds) ");
		sql.append("GROUP BY company_id ");
		Query query = em.createNativeQuery(sql.toString());
		query.setParameter("companyIds", companyIds);
		List<Object[]> list = query.getResultList();
		Map<Integer, Integer[]> map = new HashMap<Integer, Integer[]>();
		if (list != null && list.size() > 0) {
			for (Object[] obj : list) {
				Number concurrentNum = (Number) obj[1];
				Number robotNum = (Number) obj[2];
				int ccNum = concurrentNum == null ? 1 : concurrentNum.intValue();
				int rbNum = robotNum == null ? 1 : robotNum.intValue();
				Integer[] array = { ccNum, rbNum };
				map.put(Integer.valueOf(obj[0].toString()), array);
			}
		}
		return map;

	}

	/**
	 * 查看详情
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public CompanyInfo findDetail(Integer companyId) {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"SELECT c.agents_id AS agentsId, c.company_id AS companyId, c.sys_name AS sysName, c.short_name AS shortName,");
		sql.append(
				"c.company_name AS companyName, c.sale_name AS saleName, c.industry_id AS industryId, c.insert_time AS insertTime,");
		sql.append(
				"a.city AS provinceName,b.city AS cityName, c.agents_name AS agentsName, c.account_manager_name AS accountManagerName ");
		sql.append(
				"FROM tb_company_info c LEFT JOIN tb_area a ON a.CODE = c.province_code LEFT JOIN tb_area b ON b.CODE = c.city_code ");
		if (null != companyId) {
			sql.append("WHERE c.company_id =:companyId ");
		}
		Query query = em.createNativeQuery(sql.toString());
		query.setParameter("companyId", companyId);
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(CompanyInfo.class));
		// 返回对象
		CompanyInfo companyInfo = (CompanyInfo) query.getSingleResult();
		UserInfo userInfo = userInfoService.findManagerByCompanyId(companyId);
		if (userInfo != null) {
			companyInfo.setUserName(userInfo.getUserName());
			companyInfo.setLoginName(userInfo.getLoginName());
			companyInfo.setPhone(userInfo.getPhone());
		}
		return companyInfo;
	}

	@Transactional(readOnly = true)
	public List<CompanyInfo> findAllCompany() {
		Sort sort = new Sort(Direction.ASC, "companyName");
		return companyInfoRepository.findAll(sort);
	}

	/**
	 * 通过公司id集合查询通道数
	 * 
	 * @param companyIds
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public Map<String, Integer> findChannelNumByCompanyIds(Set<Integer> companyIds) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		if (null != companyIds && companyIds.size() > 0) {
			
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT company_id, COUNT(1) AS num ");
			sql.append("FROM tb_company_channel ");
			sql.append("WHERE company_id IN (:companyIds) AND is_delete = 0 AND channel_status=1 ");
			sql.append("GROUP BY company_id ");
			Query query = em.createNativeQuery(sql.toString());
			query.setParameter("companyIds", companyIds);
			
			List<Object[]> list = query.getResultList();
			if (list != null && list.size() > 0) {
				for (Object[] obj : list) {
					Number companyId = (Number) obj[0];
					Number channelCount = (Number) obj[1];
					String cid = companyId.toString();
					int cnum = channelCount.intValue();
					map.put(cid, cnum);
				}
			}
		}
		return map;
	}

	

	/**
	 * 初始化tb_data_filter_rule相关数据
	 * 
	 * @param companyId
	 */
	public void initDataFilter(Integer companyId) {
		String sql1 = "INSERT INTO tb_platform_parameter(instenceid,is_delete,module_name,par_describe,par_items,par_value_coll,code,company_id)SELECT instenceid,is_delete,module_name,par_describe,par_items,par_value_coll,code,"
				+ companyId + " FROM tb_platform_parameter WHERE company_id=1";
		em.createNativeQuery(sql1).executeUpdate();
		String sql2 = "INSERT INTO `tb_data_filter_rule` ( `company_id`, `condition_jpql`, `model_class_name`, `name`, `operation_type`, `relation_id`, `companyId`) VALUES ( "
				+ companyId
				+ ", 'createUser.userId=:userId', 'cn.com.qytx.hotline.phonetask.domain.PhoneTask', '平台用户,只能查询自己创建的任务', 'READ', 'role_ep_platform', '1')";
		em.createNativeQuery(sql2).executeUpdate();
		String sql3 = "INSERT INTO `tb_data_filter_rule` ( `company_id`, `condition_jpql`, `model_class_name`, `name`, `operation_type`, `relation_id`, `companyId`) VALUES ( "
				+ companyId
				+ ", 'createUserId=:userId', 'cn.com.qytx.mashine.channel.domain.Channel', '平台用户,只能查询自己创建的通道号码', 'READ', 'role_ep_platform', '1')";
		em.createNativeQuery(sql3).executeUpdate();
	}


	/**
	 * 查询代理商的下的公司集合
	 * 
	 * @param agentsId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<CompanyInfo> findByAgentsIdOrderByCompanyId(Integer agentsId) {
		return companyInfoRepository.findByAgentsIdOrderByCompanyId(agentsId);
	}

	/**
	 * @param keyword
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Page<CompanyInfo> findByKeyword(Integer keywordType, String keyword, Pageable pageable) {
		List<Object> params = new LinkedList<Object>();

		StringBuffer sql = new StringBuffer();
		sql.append("FROM tb_company_info ");
		String where = this.findByKeywordAppendWhere(keywordType, keyword, params);
		if (StringUtils.isNotEmpty(where)) {
			sql.append(where);
		}

		Query countQuery = em.createNativeQuery("SELECT count(1) as total " + sql.toString());
		if (!params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				countQuery.setParameter(i + 1, params.get(i));
			}
		}
		Number total = (Number) countQuery.getSingleResult();
		
		// 校正页码
		int realPageNum = super.correctionPageNum(total.intValue(), pageable.getPageSize(), pageable.getPageNumber());

		StringBuffer selectSql = new StringBuffer();
		selectSql.append(
				"SELECT company_id as companyId, company_name as companyName, industry_id as industryId, address as address ");
		selectSql.append(
				", sale_id as saleId, sale_name as saleName, account_manager_id as accountManagerId, account_manager_name as accountManagerName ");
		selectSql.append(
				", gw_name as gwName ,insert_time as insertTime, call_state_authority as callStateAuthority,support_dialect as supportDialect ");
		selectSql.append(", special_power as specialPower ");
		Query contentQuery = em.createNativeQuery(selectSql.toString() + sql.toString() + "ORDER BY companyId DESC ");
		if (!params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				contentQuery.setParameter(i + 1, params.get(i));
			}
		}
		contentQuery.setFirstResult(realPageNum * pageable.getPageSize());
		contentQuery.setMaxResults(pageable.getPageSize());

		contentQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(CompanyInfo.class));
		List<CompanyInfo> content = contentQuery.getResultList();

		PageSupport newPageSupport = new PageSupport();
		newPageSupport.setPageNumber(realPageNum);
		newPageSupport.setPageSize(pageable.getPageSize());
		return new PageImpl(content, newPageSupport.getPage(), total.longValue());
	}

	private String findByKeywordAppendWhere(Integer keywordType, String keyword, List<Object> params) {
		Integer companyId = null;
		try {
			companyId = Integer.parseInt(keyword.trim());
		} catch (NumberFormatException nfe) {

		}

		StringBuffer sql = new StringBuffer();
		if (keywordType == 1 && StringUtils.isNotEmpty(keyword)) {
			sql.append("AND company_name = ? ");
			params.add(keyword);
		}
		if (keywordType == 2 && StringUtils.isNotEmpty(keyword)) {
			if (companyId != null) {
				sql.append("AND company_id = ? ");
				params.add(companyId);
			} else {
				sql.append("AND company_id = -1 ");
			}
		}
		if (keywordType == 3 && StringUtils.isNotEmpty(keyword)) {
			sql.append(
					"AND company_id in (SELECT ui.company_id FROM ( SELECT MIN(user_id) AS userId FROM tb_user_info WHERE is_delete = 0 GROUP BY company_id ) t0 INNER JOIN tb_user_info ui ON ui.user_id = t0.userId WHERE ui.login_name = ? ) ");
			params.add(keyword);
		}
		if (keywordType == 4 && StringUtils.isNotEmpty(keyword)) {
			sql.append("AND gw_name = ? ");
			params.add(keyword);
		}
		if (keywordType == 5 && StringUtils.isNotEmpty(keyword)) {
			sql.append("AND gw_tag = ? ");
			params.add(keyword);
		}
		if (keywordType == 0 && StringUtils.isNotEmpty(keyword)) {
			String whereOrSql = appendWhereOrSql(keyword, companyId, keyword, keyword, keyword, params);
			if (whereOrSql != null) {
				sql.append(whereOrSql);
			}
		}

		if (sql.length() > 0) {
			sql.delete(0, "AND ".length());
			sql.insert(0, "WHERE ");
		}

		return sql.toString();
	}

	/**
	 * 关键字OR拼接
	 * 
	 * @param companyName
	 * @param companyId
	 * @param loginName
	 * @param voxGatewayName
	 * @param channelName
	 * @param channelNum
	 * @param params
	 * @return
	 */
	private String appendWhereOrSql(String companyName, Integer companyId, String loginName, String gwName,
			String gwTag, List<Object> params) {
		StringBuffer sql = new StringBuffer();

		if (StringUtils.isNotEmpty(companyName)) {
			sql.append("OR company_name LIKE ? ");
			params.add("%" + companyName + "%");
		}
		if (companyId != null) {
			sql.append("OR company_id = ? ");
			params.add(companyId);
		}
		if (StringUtils.isNotEmpty(loginName)) {
			sql.append(
					"OR company_id in (SELECT ui.company_id FROM ( SELECT MIN(user_id) AS userId FROM tb_user_info WHERE is_delete = 0 GROUP BY company_id ) t0 INNER JOIN tb_user_info ui ON ui.user_id = t0.userId WHERE ui.login_name LIKE ? ) ");
			params.add("%" + loginName + "%");
		}
		if (StringUtils.isNotEmpty(gwName)) {
			sql.append("OR gw_name LIKE ? ");
			params.add("%" + gwName + "%");
		}
		if (StringUtils.isNotEmpty(gwTag)) {
			sql.append("OR gw_tag LIKE ? ");
			params.add("%" + gwTag + "%");
		}
		if (sql.length() > 0) {
			sql.delete(0, "OR ".length());
			return "AND (" + sql.toString() + ") ";
		}

		return null;
	}

	/**
	 * 验证 公司名称是否重复
	 * 
	 * @param companyId
	 * @param companyNname
	 * @return
	 */
	@Transactional(readOnly = true)
	public CompanyInfo verifyCompanyNameUnique(Integer companyId, String companyName) {
		StringBuffer hql = new StringBuffer();
		hql.append("FROM CompanyInfo WHERE companyName = :companyName AND enableStatus = :enableStatus ");
		if (companyId != null) {
			hql.append("AND companyId != :companyId ");
		}
		Query query = em.createQuery(hql.toString());
		query.setParameter("companyName", companyName);
		query.setParameter("enableStatus", 1);
		if (companyId != null) {
			query.setParameter("companyId", companyId);
		}
		query.setMaxResults(1);
		CompanyInfo companyInfo = null;
		try {
			companyInfo = (CompanyInfo) query.getSingleResult();
		} catch (NoResultException nre) {

		}
		return companyInfo;
	}
	
	/**
	 * 卡券管理-发放-查询发放对象
	 * @param companyName
	 * @param provinceCode
	 * @param cityCode
	 * @param industryId
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<CompanyInfo> find4GrantCardCompany(String companyName, String provinceCode, String cityCode, Integer industryId, Pageable pageable) {
		List<Object> params = new LinkedList<Object>();

		/* 拼接select语句 */
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("SELECT ci.company_id AS companyId, ci.company_name AS companyName ");
		selectSql.append(", ci.industry_id AS industryId ");
		selectSql.append(", ci.province_code AS provinceCode, ci.city_code AS cityCode ");
		selectSql.append(", ci.address AS address ");

		/* 拼接from + where语句 */
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append("FROM tb_company_info ci ");
		fromWhereSql.append(find4GrantCardCompanyAppendWhere(companyName, provinceCode, cityCode, industryId, params));

		String orderBySql = "ORDER BY ci.company_id DESC ";

		// 查询列表数据
		return super.findPageBySql(CompanyInfo.class, selectSql.toString(), fromWhereSql.toString(), orderBySql, params,
				pageable);
	}
	
	/**
	 * 
	 * @param companyName
	 * @param provinceCode
	 * @param cityCode
	 * @param industryId
	 * @param params
	 * @return
	 */
	private String find4GrantCardCompanyAppendWhere(String companyName, String provinceCode, String cityCode, Integer industryId, List<Object> params) {

		StringBuffer sql = new StringBuffer();
		if (StringUtils.isNotEmpty(companyName)) {
			sql.append("AND ci.company_name LIKE ? ");
			params.add("%" + companyName + "%");
		}
		if (StringUtils.isNotEmpty(provinceCode)) {
			sql.append("AND ci.province_code = ? ");
			params.add(provinceCode);
		}
		if (StringUtils.isNotEmpty(cityCode)) {
			sql.append("AND ci.city_code = ? ");
			params.add(cityCode);
		}
		if (industryId != null) {
			sql.append("AND ci.industry_id = ? ");
			params.add(industryId);
		}
		if (sql.length() > 0) {
			sql.delete(0, "AND ".length());
			sql.insert(0, "WHERE ");
		}

		return sql.toString();
	}
	
	/**
	 * 通过公司id集合公司对象查询
	 * 
	 * @param companyIds
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<CompanyInfo> findByCompanyIds(Collection<Integer> companyIds) {
		if (companyIds == null || companyIds.isEmpty()) {
			return null;
		}
		
		StringBuffer hql = new StringBuffer();
		hql.append("FROM CompanyInfo ");
		hql.append("WHERE companyId IN (:companyIds) ");
		
		Query query = em.createQuery(hql.toString());
		query.setParameter("companyIds", companyIds);
		
		return query.getResultList();
	}
	
	/**
	 * 通过公司id集合公司对象查询
	 * 
	 * @param companyId
	 * @param companyName
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<CompanyInfo> find4PayAccount(Integer companyId, String companyName, Pageable pageable) {
		
		Page<CompanyInfo> page = companyInfoRepository.findAll(new Specification<CompanyInfo> () {

			@Override
			public Predicate toPredicate(Root<CompanyInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p1 = null;
				if (companyId != null) {
					p1 = cb.equal(root.get("companyId"), companyId);
				}
				
				if (StringUtils.isNotEmpty(companyName)) {
					Predicate p2 = cb.like(root.get("companyName"), "%"+companyName+"%");
					if (p1 != null) {
						p1 = cb.and(p1, p2);
					} else {
						p1 = p2;
					}
                }
				return p1;
			}
			
		}, pageable);
		
		return page;
	}

}
